// GameEntities.cpp

#include "include/GameEntities.h"


void ResourceManager::loadResourceImage(int x, int y, UINT resID) {
    HINSTANCE hInst = GetModuleHandle(NULL);
    HBITMAP hBitmap = (HBITMAP)LoadImage(hInst, MAKEINTRESOURCE(resID), IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);

    if (hBitmap) {
        HDC hdcMem = CreateCompatibleDC(NULL);
        SelectObject(hdcMem, hBitmap);

        BITMAP bm;
        GetObject(hBitmap, sizeof(BITMAP), &bm);

        HDC hdcScreen = GetImageHDC(NULL);
        BitBlt(hdcScreen, x, y, bm.bmWidth, bm.bmHeight, hdcMem, 0, 0, SRCCOPY);

        DeleteDC(hdcMem);
        DeleteObject(hBitmap);
    }
}

// Method to move the player based on the given direction
bool Player::move(vector<vector<Tile>>& map_player, Direction dir) {
    switch (dir) {
    case UP: dy = -1; break;
    case DOWN: dy = 1; break;
    case LEFT: dx = -1; break;
    case RIGHT: dx = 1; break;
    }

    int px, py;
    // Find player's position
    for (int y = 0; y < HEIGHT; ++y) {
        for (int x = 0; x < WIDTH; ++x) {
            if (map_player[y][x] == PLAYER || map_player[y][x] == PLAYER_ON_GOAL) {
                px = x; py = y;
                break;
            }
        }
    }

    // Check boundaries and walls 
    if (px + dx < 0 || px + dx >= WIDTH || py + dy < 0 || py + dy >= HEIGHT || map_player[py + dy][px + dx] == WALL) {
        // If the next position is outside the map or a wall, don't move.
        return false;
    }

    Tile& current = map_player[py][px];
    Tile& next = map_player[py + dy][px + dx];
    Tile& afterNext = map_player[py + 2 * dy][px + 2 * dx];

    // Move logic for FLOOR, GOAL, and BOX
    if (next == BOX && (afterNext == FLOOR || afterNext == GOAL)) {
        // Move box and player
        afterNext = (afterNext == GOAL) ? BOX_ON_GOAL : BOX;
        next = (current == PLAYER_ON_GOAL) ? PLAYER_ON_GOAL : PLAYER;
        current = (current == PLAYER_ON_GOAL) ? GOAL : FLOOR;
    }
    else if (next == BOX_ON_GOAL && (afterNext == FLOOR || afterNext == GOAL)) {
        // If the box is on a goal and there's floor or another goal behind it, move the box and the player
        afterNext = (afterNext == GOAL) ? BOX_ON_GOAL : BOX; 
        //The player moves to the position of the box at the goal point
        next = PLAYER_ON_GOAL;
        // If the current point is the goal point, leave the goal point, otherwise leave a floor
        current = (current == PLAYER_ON_GOAL) ? GOAL : FLOOR;
    }
    else if (next == FLOOR) {
        // Move player to floor
        current = (current == PLAYER_ON_GOAL) ? GOAL : FLOOR;
        next = PLAYER;
    }
    else if (next == GOAL) {
        // Player moves onto goal tile
        current = (current == PLAYER_ON_GOAL) ? GOAL : FLOOR;
        next = PLAYER_ON_GOAL;
    }
    else {
        // Cannot move (next is WALL or BOX with no space behind)
        return false;
    }
    return true;
}